package com.goo.utils;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.StreamGobbler;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @desc: shh 远程调用linux命令
 * @author: wangsh
 */
public class SSH2Utils {

    private static final String charset = Charset.defaultCharset().toString();
    //连接超时时间
    private static final int TIME_OUT = 1000 * 5 * 60;

    private SSH2Utils() {
    }

    public static SSH2Utils getInstance() {
        return new SSH2Utils();
    }

    /**
     * 登录
     *
     * @return
     * @throws IOException
     */
    public static Connection connect(String host, int port, String userName, String password) throws IOException {
        Connection conn = new Connection(host, port);
        conn.connect();//建立连接
        boolean b = conn.authenticateWithPassword(userName, password);
        if (b) {
            return conn;
        } else {
            throw new RuntimeException("登录远程机器失败" + host);
        }
    }

    /**
     * 执行脚本
     *
     * @param cmds
     * @return
     * @throws Exception
     */
    public static String exec(Connection connection, String cmds) throws Exception {
        String outStr = "";
        String outErr = "";
        try {
            //建立session
            ch.ethz.ssh2.Session session = connection.openSession();
            //执行远程机器命令
            session.execCommand(cmds);

            //获取输出信息
            outStr = read(new StreamGobbler(session.getStdout()), charset);
            outErr = read(new StreamGobbler(session.getStderr()), charset);

            //此方法将阻塞，直到底层SSH-2通道上的某些条件成立为止
            session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);

            int ret = session.getExitStatus();
            System.out.println("通道状态（-1标识退出）：" + ret);

            System.out.println("执行命令结果：" + outStr);
            System.out.println("执行命令错误信息： " + outErr);
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
        return outStr;
    }

    /**
     * 读取输出结果
     *
     * @param in
     * @param charset
     * @return
     * @throws IOException
     */
    private static String read(InputStream in, String charset) throws IOException {
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while (in.read(buf) != -1) {
            sb.append(new String(buf, charset));
        }
        return sb.toString();
    }

    /**
     * 关闭
     *
     * @param connection
     */
    public static void close(Connection connection) {
        if (connection != null) {
            connection.close();
        }
    }

    public static void main(String args[]) throws Exception {

        String cmd = "cd /usr/local/" + ";" + "netstat -ntlp";
        Connection connection = SSH2Utils.connect("8.135.42.12", 22, "root", "Dszn@2020");
        String response = SSH2Utils.exec(connection, cmd);
        System.out.println("执行结果：" + response);
    }

}
